/*
 * @lc app=leetcode.cn id=71 lang=cpp
 *
 * [71] 简化路径
 */

// @lc code=start
class Solution {
public:
    string simplifyPath(string path) {

        //使用 vector 充当栈 (stack) 无法随机访问。。。
        std::vector<std::string> p;

        //查询时需要将最后一段找出
        path += '/';

        path = path.substr(1);
        for (int i = path.find_first_of('/'); i != std::string::npos; 
                path = path.substr(i + 1), i = path.find_first_of('/')) 
        {
            auto name = path.substr(0, i);
            if (name == "." || name.size() == 0) {
                continue;
            }
            
            else if (name == "..")
                if (p.size() > 0) 
                    p.pop_back();
                else
                    continue;

            else 
                p.push_back(std::move(name));
        }
        
        if (p.empty())
            return "/";

        std::string result;

        for (int i = 0; i < p.size(); i++)
            result += ("/" + std::move(p[i]));


        return result;
    }
};
// @lc code=end

